<template>
  <!-- 自定义组件 -->
  <x-search>
    <!-- 搜索的一系列东西 -->
    <template #search>
      <p>
        <a-input
          v-model:value="student_name"
          placeholder="请输入学生姓名"
          style="width: 150px"
        />
      </p>
      <p style="margin-left: 10px">
        <a-select
          v-model:value="class_id"
          placeholder="查询班级"
          style="width: 120px"
        >
          <a-select-option
            v-for="(value, index) in all_classes"
            :key="index"
            :value="value.id"
          >
            <span>{{ value.name }}</span>
          </a-select-option>
        </a-select>
      </p>
      <p style="margin-left: 10px">
        <a-range-picker
          v-model:value="rankDate"
          :disabled-date="disabledDate"
          style="width: 220px"
        />
      </p>
      <a-button type="primary" style="margin-left: 10px" @click="but_search">
        <search-outlined style="margin-right: 5px" />
        查询</a-button
      >
      <a-button style="margin-left: 10px" @click="reset_search"
        ><redo-outlined style="margin-right: 5px" />重置</a-button
      >
    </template>
    <!-- 操作的一系列东西 -->
    <template #operate>
      <a-button
        type="primary"
        style="background: #52c41a; border-color: #52c41a"
      >
        <template #icon><export-outlined style="margin-right: 5px" /></template>
        导出</a-button
      >
    </template>
  </x-search>

  <!-- 统计图部分2个 -->
  <div class="chart">
    <!-- 学生成绩对比统计图 -->
    <x-card :message="message1" :width="49" :height="height1">
      <div ref="chartRef1" style="width: 100%; height: 300px"></div>
    </x-card>

    <!-- 班级平均分趋势图 -->
    <x-card :message="message2" :width="49" :height="height1">
      <div ref="chartRef2" style="width: 100%; height: 300px"></div>
    </x-card>
  </div>

  <!-- 表格区 -->
  <!-- 数据表格 -->
  <a-table
    :dataSource="tableData"
    :columns="columns"
    :pagination="pagination"
    bordered
    style="margin-top: 10px"
    @change="handleTableChange"
    :scroll="{ x: 1300, y: 200 }"
  >
    <!-- <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'average_score'">
        {{ record.average_score }}%
      </template>
    </template> -->
  </a-table>
</template>
  
  <script setup lang="ts">
import BreadCrumb from "./BreadCrumb.vue";
import XCard from "./XCard.vue";
import XSearch from "./XSearch.vue";
import {
  ref,
  reactive,
  toRaw,
  onMounted,
  createVNode,
  watch,
  computed,
} from "vue";
import http from "../routerutils/http";
import { message, Modal, Cascader } from "ant-design-vue";
// 对话提示
import {
  SearchOutlined,
  FileTextOutlined,
  TeamOutlined,
  UserOutlined,
  ReadOutlined,
  BookOutlined,
  RedoOutlined,
  ExportOutlined,
} from "@ant-design/icons-vue";
// 表单验证
import type { Rule } from "ant-design-vue/es/form";
import type { UnwrapRef, onUnmounted } from "vue";
import type { CascaderProps } from "ant-design-vue";
import { number } from "echarts";
import type { Dayjs } from "dayjs";
// 处理时间
import dayjs from "dayjs";
import * as echarts from "echarts";
import { TableProps } from "ant-design-vue";
import { anyType } from "ant-design-vue/es/_util/type";

interface ClassInfo {
  id: string;
  name: string;
}

// 1. 搜索相关的操作数据
const student_name = ref<string>("");
const class_id = ref();
const rankDate = ref<[Dayjs, Dayjs]>([null, null]);
// const exam_date = ref<[Dayjs, Dayjs]>();
const disabledDate = (current: Dayjs) => {
  return current && current > dayjs().endOf("day");
};

// 重置按钮的方法
const reset_search = () => {
  student_name.value = "";
  class_id.value = null;
  rankDate.value = [null, null];
  fetchData();
  initChart1();
  initChart2();
};

// 搜索按钮的方法
const but_search = () => {
  fetchData();
  initChart1();
  initChart2();
};

// 后端接口所有班级数据
const all_classes = ref<ClassInfo[]>([]);
const all_class = async () => {
  try {
    const response = await http.get("/api/students/allclass");
    all_classes.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};

onMounted(() => {
  all_class();
});

// 学生成绩对比统计图
const message1 = ref<string>("学生成绩对比统计图");
const height1 = ref<string>("400px");
const chartRef1 = ref<HTMLElement | null>(null);
let chartInstance1: echarts.ECharts | null = null;
const initChart1 = async () => {
  try {
    const response = await http.get("/api/analysis/allScore", {
      params: {
        start_time: rankDate.value?.[0]?.format("YYYY-MM-DD"),
        end_time: rankDate.value?.[1]?.format("YYYY-MM-DD"),
      },
    });

    const scoreData = response.data.results.map((item: any) => item.score_all);

    // 定义分数段
    const scoreRanges = [
      { name: "0分", range: [0, 0] },
      { name: "1-59分", range: [1, 59] },
      { name: "60-69分", range: [60, 69] },
      { name: "70-79分", range: [70, 79] },
      { name: "80-89分", range: [80, 89] },
      { name: "90-100分", range: [90, 100] },
    ];

    // 统计各分数段人数
    const rangeCounts = scoreRanges.map((range) => {
      return scoreData.filter(
        (score: number) => score >= range.range[0] && score <= range.range[1]
      ).length;
    });

    // 计算百分比
    const total = scoreData.length;
    const percentages = rangeCounts.map((count) =>
      total > 0 ? ((count / total) * 100).toFixed(1) : 0
    );

    // 初始化图表
    if (!chartInstance1 && chartRef1.value) {
      chartInstance1 = echarts.init(chartRef1.value);
    }

    // 配置项
    const option = {
      title: {
        text: "学生成绩分布统计",
        subtext: `总人数: ${total}人`,
        left: "center",
        textStyle: {
          color: "#333",
          fontSize: 16,
        },
      },
      tooltip: {
        trigger: "axis",
        formatter: (params: any) => {
          const data = params[0];
          return `
            <div style="font-weight:bold">${data.name}</div>
            <div>人数: ${rangeCounts[data.dataIndex]}人</div>
            <div>占比: ${data.value}%</div>
          `;
        },
        axisPointer: {
          type: "shadow",
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: scoreRanges.map((r) => r.name),
        axisLabel: {
          interval: 0,
          rotate: 0,
        },
        axisLine: {
          lineStyle: {
            color: "#ccc",
          },
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      yAxis: {
        type: "value",
        name: "占比(%)",
        min: 0,
        max: 100,
        axisLabel: {
          formatter: "{value}%",
        },
        splitLine: {
          lineStyle: {
            type: "dashed",
          },
        },
      },
      series: [
        {
          name: "成绩分布",
          type: "line",
          smooth: true,
          data: percentages,
          symbol: "circle",
          symbolSize: 8,
          itemStyle: {
            color: "#5470C6",
          },
          lineStyle: {
            width: 3,
            color: "#5470C6",
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(84, 112, 198, 0.5)" },
              { offset: 1, color: "rgba(84, 112, 198, 0.1)" },
            ]),
          },
          label: {
            show: true,
            position: "top",
            formatter: "{c}%",
          },
        },
      ],
      animationDuration: 1000,
      animationEasing: "cubicOut",
    };

    // 初始化或更新图表
    if (!chartInstance1) {
      chartInstance1 = echarts.init(chartRef1.value);
    }
    chartInstance1.setOption(option);

    // 窗口自适应
    window.addEventListener("resize", () => chartInstance1?.resize());

    // 窗口自适应
    window.addEventListener("resize", () => chartInstance1?.resize());
  } catch (error) {
    console.error("成绩数据加载失败:", error);
    message.error("成绩分布数据加载失败");
  }
};

// 班级平均分趋势图
const message2 = ref<string>("班级平均分趋势图");
const chartRef2 = ref<HTMLElement | null>(null);
let chartInstance2: echarts.ECharts | null = null;

const initChart2 = async () => {
  try {
    const response = await http.get("/api/analysis/average", {
      params: {
        start_time: rankDate.value[0],
        end_time: rankDate.value[1],
      },
    });
    const averageData = response.data.results;
    const classNames = averageData.map((item: any) => {
      return item.class_name;
    });
    const averages = averageData.map((item: any) => ({
      name: item.class_name,
      value: item.average_score, // 分数
      examDate: item.exam_date, // 日期
    }));
    // 初始化图表
    if (!chartInstance2 && chartRef2.value) {
      chartInstance2 = echarts.init(chartRef2.value);
    }

    // 配置项
    const option = {
      title: {
        text: "班级平均分统计",
        left: "center",
        textStyle: {
          color: "#333",
          fontSize: 16,
        },
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: (params: any) => {
          const data = params[0].data;
          return `${data.name}<br/>平均分: ${data.value}分<br/>日期：${data.examDate}`;
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: classNames,
        axisLabel: {
          interval: 0,
          rotate: 30, // 班级名较长时可旋转
        },
      },
      yAxis: {
        type: "value",
        name: "平均分",
        min: 0,
        max: 100,
        axisLabel: {
          formatter: "{value}分",
        },
        splitLine: {
          lineStyle: {
            type: "dashed",
          },
        },
      },
      series: [
        {
          name: "班级平均分",
          type: "bar",
          data: averages,
          itemStyle: {
            color: (params: any) => {
              // 根据分数设置不同颜色
              const score = params.value;
              if (score >= 85) return "#67C23A"; // 优秀-绿色
              if (score >= 70) return "#409EFF"; // 良好-蓝色
              if (score >= 60) return "#E6A23C"; // 及格-黄色
              return "#F56C6C"; // 不及格-红色
            },
          },
          label: {
            show: true,
            position: "top",
            formatter: "{c}分",
          }
        },
      ],
      animationDuration: 1000,
    };

    chartInstance2?.setOption(option);

    // 窗口自适应
    window.addEventListener("resize", () => chartInstance2?.resize());
  } catch (error) {
    console.error("成绩数据加载失败:", error);
    message.error("班级平均分数据加载失败");
  }
};

// 表格区域操作
// 定义数据类型
interface TableItem {
  rank: number;
  student_name: string;
  class_name: string;
  total_score: number;
  average_score: number;
}

// 表格状态
const tableData = ref<TableItem[]>([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ["5", "10", "20"],
  showTotal: (total: number) => `共 ${total} 条`,
});

// 列定义
const columns: TableProps["columns"] = [
  {
    title: "班级排名",
    dataIndex: "rank",
    width: 80,
    fixed: "left",
    sorter: true,
  },
  {
    title: "学生姓名",
    dataIndex: "student_name",
    width: 120,
    sorter: true,
  },
  {
    title: "班级",
    dataIndex: "class_name",
    width: 150,
  },
  {
    title: "总分",
    dataIndex: "total_score",
    sorter: true,
    width: 100,
  },
  {
    title: "平均分",
    dataIndex: "average_score",
    sorter: true,
    width: 120,
  },
];

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const params = {
      name: student_name.value,
      classes_id: class_id.value,
      start_time: rankDate.value[0],
      end_time: rankDate.value[1],
      page: pagination.value.current,
      page_size: pagination.value.pageSize,
    };

    const response = await http.get("/api/analysis/student", { params });
    tableData.value = response.data.results;
    pagination.value.total = response.data.results.length;
  } catch (error) {
    console.error("数据加载失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理表格变化
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  // 更新分页
  pagination.value = { ...pagination.value, ...pag };

  // 更新筛选
  filters.value = {
    name: filters.student_name?.[0],
    classes_id: filters.class_name?.[0],
  };

  // 排序处理
  if (sorter.field) {
    console.log("排序字段:", sorter.field, "方向:", sorter.order);
  }

  fetchData();
};

onMounted(() => {
  initChart1();
  initChart2();
  fetchData();
});
</script>
  
  <style scoped>
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
.chart {
  display: flex;
  justify-content: space-between;
}
</style>